<template>
  <view class="business-list-container">
    <!-- 下拉刷新组件 -->
    <!-- 顶部轮播图 -->
    <view class="carousel-section">
      <swiper
        class="carousel-swiper"
        :indicator-dots="true"
        :autoplay="true"
        :interval="3000"
        :duration="500"
        indicator-color="rgba(255,255,255,0.5)"
        indicator-active-color="#fff"
      >
        <swiper-item v-for="(item, index) in carouselImages" :key="index">
          <image
            :src="item.image"
            class="carousel-image"
            mode="aspectFill"
            @tap="handleCarouselClick(item)"
          />
        </swiper-item>
      </swiper>
    </view>

    <!-- 搜索区域 -->
    <view class="search-section">
      <view class="search-box">
        <input
          v-model="searchKeyword"
          class="search-input"
          placeholder="搜索企业名称或简介..."
          confirm-type="search"
          @confirm="handleSearch"
        />
        <button class="search-btn" @tap="handleSearch">
          <text class="search-icon">🔍</text>
          搜索
        </button>
      </view>
    </view>

    <!-- 企业列表 -->
    <view class="business-list-section">
      <view class="list-header">
        <text class="list-title">商企联谊</text>
        <text class="list-count">共 {{ businessList.length }} 家企业</text>
      </view>

      <scroll-view class="business-scroll" scroll-y :scroll-top="scrollTop">
        <view
          v-for="(business, index) in businessList"
          :key="business.id"
          class="business-card"
          @tap="handleBusinessDetail(business)"
        >
          <!-- 企业图片 -->
          <view class="business-image-wrapper">
            <image
              :src="business.cover || defaultBusinessLogo"
              class="business-logo"
              mode="aspectFill"
              @error="handleImageError(index)"
            />
          </view>

          <!-- 企业信息 -->
          <view class="business-info">
            <!-- 家谱角色标签 -->
            <!-- <view class="role-tag" :class="getRoleClass(business.tags)">
              {{ business.tags || "未知" }}
            </view> -->
            
            <!-- 公司名称 -->
            <text class="business-name">{{ business.name }}</text>
            <!-- 企业名称 -->
            <text class="company-name">{{ business.realname }}</text>
            <!-- 公司简介 -->
            <text class="business-intro" :class="{ ellipsis: !business.expanded }">
              {{ business.address }}
            </text>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="loading" class="loading-more">
          <text>加载中...</text>
        </view>

        <!-- 无数据提示 -->
        <view v-if="businessList.length === 0 && !loading" class="empty-state">
          <image class="empty-icon" src="/static/icons/empty.png" mode="aspectFit" />
          <text class="empty-text">暂无相关企业</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
// import businessImg from "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/098ac2ad98e04576abacb6e492532470.webp";
// import businessImgT from "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/c95a05015ae64807a7910447e44fe717.webp";
import ClanMember from "@/api/genealogy/conpany";

// 获取当前页面栈（数组，最后一个元素为当前页）
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];

// 定义路由参数变量
const familyId = ref('');

// 在 onLoad 中接收参数
onLoad((options: any) => {
  if (options && options.familyId) {
    familyId.value = options.familyId;
  } else {
    // 备用方案：尝试从当前页面实例获取
    try {
      if (currentPage && currentPage.options && currentPage.options.familyId) {
        familyId.value = currentPage.options.familyId;
      }
    } catch (error) {
      console.warn('备用方案获取参数失败:', error);
    }
  }
});
// 轮播图数据
const carouselImages = ref([
  { image: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/098ac2ad98e04576abacb6e492532470.webp", title: "优秀企业展示", link: "/pages/work/business/detail" },
  { image: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/c95a05015ae64807a7910447e44fe717.webp", title: "企业联盟活动", link: "/pages/work/business/activity" },
]);

// 企业列表数据
const businessList = ref<Array<any>>([]);

// 默认企业logo
const defaultBusinessLogo = "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/c76cac7f6d9e4b06bb470645c38d336f.webp";

// 搜索关键词
const searchKeyword = ref("");
const loading = ref(false);
const refreshing = ref(false);
const scrollTop = ref(0);
const pageNum = ref(1);
const pageSize = ref(40);
const total = ref(0);
const hasMore = ref(true);


// familyId已在onLoad函数中初始化，此处不再重复定义
// console.log('最终的familyId值:', familyId.value);
// 搜索关键词（保留用于可能的搜索功能，但不再用于本地过滤）

// 处理搜索 - 现在直接调用接口进行搜索
const handleSearch = () => {
  scrollTop.value = 0;
  pageNum.value = 1;
  getCompanyList(true);
};

// 轮播图点击
const handleCarouselClick = (item: any) => {
  uni.navigateTo({
    url: item.link,
  });
};

// 企业详情
const handleBusinessDetail = (business: any) => {
  uni.navigateTo({
    url: `/pages/work/clan/busalliance/businessDetail?id=${business.id}`,
  });
};

// 展开/收起简介
const toggleExpand = (index: number) => {
  const business = businessList.value[index];
  if (business) {
    business.expanded = !business.expanded;
  }
};

// 图片加载错误处理
const handleImageError = (index: number) => {
  const business = businessList.value[index];
  if (business) {
    business.logo = defaultBusinessLogo;
  }
};

// 加载更多
const loadMore = () => {
  if (loading.value || !hasMore.value) return;

  pageNum.value += 1;
  getCompanyList();
};

// 获取角色样式类
const getRoleClass = (role: string) => {
  const roleMap: Record<string, string> = {
    会长: "role-founder",
    执行会长: "role-core",
    名誉会长: "role-strategic",
    秘书长: "role-partner",
    顾问: "role-supporter",
  };
  return roleMap[role] || "role-default";
};

// 获取企业列表
const getCompanyList = async (isRefresh = false) => {
  try {
    loading.value = true;

    const params = {
      pageNum: isRefresh ? 1 : pageNum.value,
      pageSize: pageSize.value,
      familyId: familyId.value,
      ...(searchKeyword.value && { keyword: searchKeyword.value }),
    };

    const res = await ClanMember.getCompanyPages(params);
    console.log("企业列表数据:", res);
    businessList.value = res.list || [];
  } catch (error) {
    console.error("获取企业列表失败:", error);
    uni.showToast({
      title: "网络错误，请重试",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 下拉刷新
const onRefresh = async () => {
  try {
    refreshing.value = true;
    pageNum.value = 1;
    await getCompanyList(true);
  } catch (error) {
    console.error("下拉刷新失败:", error);
  } finally {
    refreshing.value = false;
  }
};

onMounted(() => {
  console.log(2133122222222);
  // 初始化数据
  getCompanyList(true);
});
</script>

<style lang="scss" scoped>
.business-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-scroll {
  height: 100vh;
  width: 100%;
}

/* 轮播图样式 */
.carousel-section {
  width: 100%;
  height: 400rpx;
  background: #fff;
  margin-bottom: 20rpx;
}

.carousel-swiper {
  width: 100%;
  height: 100%;
}

.carousel-image {
  width: 100%;
  height: 100%;
}

/* 搜索区域样式 */
.search-section {
  padding: 20rpx 30rpx;
  background: #fff;
  margin-bottom: 20rpx;
}

.search-box {
  display: flex;
  align-items: center;
  background: #f8f8f8;
  border-radius: 50rpx;
  padding: 10rpx 20rpx;
}

.search-input {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
  color: #333;
  padding: 0 20rpx;
}

.search-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #007aff;
  color: #fff;
  border: none;
  border-radius: 50rpx;
  padding: 0 30rpx;
  height: 60rpx;
  font-size: 28rpx;
  margin-left: 10rpx;
}

.search-icon {
  margin-right: 10rpx;
  font-size: 28rpx;
}

/* 企业列表样式 */
.business-list-section {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  min-height: calc(100vh - 520rpx);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.list-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.list-count {
  font-size: 24rpx;
  color: #999;
}

.business-scroll {
  height: calc(100vh - 620rpx);
}

.business-card {
  display: flex;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: #fff;
  transition: all 0.3s ease;

  &:active {
    background: #f8f8f8;
  }
}

.business-image-wrapper {
  flex-shrink: 0;
  width: 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  background: #f8f8f8;
}

.business-logo {
  width: 100%;
  height: 100%;
}

.business-info {
  flex: 1;
  min-width: 0;
}

.role-tag {
  display: inline-block;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  margin-bottom: 10rpx;
  margin-right: 10rpx;

  &.role-founder {
    background: #ff4d4f;
    color: #fff;
  }

  &.role-core {
    background: #1890ff;
    color: #fff;
  }

  &.role-strategic {
    background: #52c41a;
    color: #fff;
  }

  &.role-partner {
    background: #faad14;
    color: #fff;
  }

  &.role-supporter {
    background: #722ed1;
    color: #fff;
  }

  &.role-default {
    background: #d9d9d9;
    color: #666;
  }
}

.business-name {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.company-name {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 12rpx;
}

.business-intro {
  display: block;
  font-size: 24rpx;
  color: #999;
  line-height: 1.5;

  &.ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
}

.expand-btn {
  display: inline-block;
  color: #007aff;
  font-size: 24rpx;
  margin-top: 8rpx;
}

.loading-more {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  color: #999;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>
